﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using FrontDisplay.Controls;
using MPlayer.Common;

namespace FrontDisplay.Music
{
    public class MusicPlugin : PluginBase
    {
        public MusicClientManager Player;
        public MusicPage MusicPage;
        public PlaylistPage PlaylistPage;
        //private MusicPlayerSelection MusicPlayerSelection;
        private Label _songPanel;
        private readonly Label _menuButton;
        private DispatcherTimer _idleTimer = new DispatcherTimer();
        private Configuration _config;

        private readonly HotkeyCollection _hotkeys = new HotkeyCollection();

        public MusicPlugin()
        {
            _config = new Configuration();

            _menuButton = new Label
            {
                //TODO: store resource as embedded resource (or investigate for better solution).
                Content = new Image { Source = Utility.LoadBitmap(Properties.Resources.Music) } ,
                Padding = new Thickness(40, 0, 40, 0)
            };

            _idleTimer.Interval = new TimeSpan(0, 0, _config.IdleTimeout);
            _idleTimer.Tick += IdleTimerTick;

            _spectrumBrush = new LinearGradientBrush
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(0, 100),
                MappingMode = BrushMappingMode.Absolute
            };
            _spectrumBrush.GradientStops.Add(new GradientStop { Offset = 0 });
            _spectrumBrush.GradientStops.Add(new GradientStop { Offset = 0.5 });
            _spectrumBrush.GradientStops.Add(new GradientStop { Offset = 1 });

            //_spectrumBrush.Opacity = 0.7;
            
            ChangeSpectrumColor();
        }

        public DispatcherTimer IdleTimer
        {
            get { return _idleTimer; }
        }

        private void IdleTimerTick(object sender, EventArgs e)
        {
            _idleTimer.Stop();
            if (Global.MainPanel.Children[0] == MusicPage)
            {
                Navigation.Navigate(InfoPage.Instance);
            }
        }

        private LinearGradientBrush _spectrumBrush;

        internal Brush SpectrumBrush
        {
            get
            {
                return _spectrumBrush;
            }
        }

        public override void ThemeChanged()
        {
            ChangeSpectrumColor();
        }

        private void ChangeSpectrumColor()
        {
            Color color = ThemeManager.TextBrush.Color;
            _spectrumBrush.GradientStops[0].Color = color;
            _spectrumBrush.GradientStops[1].Color = color.Lighter().Lighter();
            _spectrumBrush.GradientStops[2].Color = ThemeManager.Background.Color.Lighter();
        }

        public override void Start()
        {
            Player = new MusicClientManager();

            MusicPage = new MusicPage(this);
            PlaylistPage = new PlaylistPage(this);
            //MusicPlayerSelection = new MusicPlayerSelection(Player);

            _songPanel = new Label { Content = new OutlineTextBlock { FontSize = 70, HorizontalAlignment = HorizontalAlignment.Left } };
            _songPanel.MouseLeftButtonDown += SongPanelMouseLeftButtonDown;

            Player.StateChanged += ((sender, param) => _songPanel.InvokedCall(PlayerStatusChanged, param.State));
            Player.SongChanged += ((sender, param) => _songPanel.InvokedCall(PlayerSongChanged, param.Song));

            PlayerSongChanged(Player.CurrentSong);

            //TODO: move hotkeys initial data to config.
            _hotkeys.Add(new HotkeyInfo {Key = Key.Z, Shift = true, Win = true}, Player.Previous);
            _hotkeys.Add(new HotkeyInfo {Key = Key.X, Shift = true, Win = true}, Player.Play);
            _hotkeys.Add(new HotkeyInfo {Key = Key.C, Shift = true, Win = true}, Player.Pause);
            _hotkeys.Add(new HotkeyInfo {Key = Key.V, Shift = true, Win = true}, Player.Stop);
            _hotkeys.Add(new HotkeyInfo {Key = Key.B, Shift = true, Win = true}, Player.Next);
            _hotkeys.Add(new HotkeyInfo {Key = Key.N, Shift = true, Win = true}, () => Navigation.Navigate(PageControl));

            _hotkeys.Register(Application.Current.MainWindow);

            Player.Connect();
        }

        private void SongPanelMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Navigation.Navigate(MusicPage, Animation.MoveDown);
        }

        private void PlayerSongChanged(ISong song)
        {
            ((OutlineTextBlock)_songPanel.Content).Text = song.ToString();
        }

        private void PlayerStatusChanged(PlayerState state)
        {
            IsActive = (state == PlayerState.Playing);
        }

        public override void Stop()
        {
            if (Player != null)
            {
                Player.Disconnect();
            }
            _hotkeys.Unregister();
        }

        public override Control PageControl
        {
            get
            {
                return MusicPage;
                //if (!Player.IsConnected && Player.Count > 1)
                //{
                //    return MusicPlayerSelection;
                //}
                //else
                //{
                //    return MusicPage;
                //}
            }
        }

        public override UIElement TopControl
        {
            get { return _songPanel; }
        }

        public override UIElement BottomControl
        {
            get { return null; }
        }

        public override UIElement ParametersControl
        {
            get
            {
                ParametersPage parameters = new ParametersPage();

                parameters.AutoShowOnPlayingCheckBox.IsChecked = _config.IsAutoShowOnPlaying;
                parameters.CloseOnIdleCheckBox.IsChecked = _config.IsCloseOnIdle;
                parameters.IdleDelayTextBox.Text = _config.IdleTimeout.ToString();

                return parameters;
            }
        }

        public override void SaveConfig(UIElement element)
        {
            ParametersPage parameters = element as ParametersPage;
            if (parameters == null) return;

            _config.IsAutoShowOnPlaying = (bool) parameters.AutoShowOnPlayingCheckBox.IsChecked;
            _config.IsCloseOnIdle = (bool) parameters.CloseOnIdleCheckBox.IsChecked;

            int idleTimeout;
            if (Int32.TryParse(parameters.IdleDelayTextBox.Text, out idleTimeout))
            {
                _config.IdleTimeout = idleTimeout;
                _idleTimer.Interval = new TimeSpan(0, 0, idleTimeout);
            }

            _config.Save();
        }

        public override string Title
        {
            get { return Def.Localization.GetString("Music.Music"); }
        }

        public override UIElement MenuButton
        {
            get { return _menuButton; }
        }

        public override ApplicationSettingsBase Config
        {
            get { return _config; }
        }
    }
}
